package cn.cloud9.designpattern.dp01singleton;

import cn.cloud9.designpattern.dp02factory.simplefactory.product.JavaCourse;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author OnCloud9
 * @description
 * @project Java
 * @date 2022年05月22日 11:04
 */
public class Singleton9 {

    private Singleton9() {}

    private static Map<String, Object> instanceContainer = new ConcurrentHashMap<>();

    public static Object getInstance(String className) {
        try {
            if (!instanceContainer.containsKey(className)) {
                Object instance = Class.forName(className).newInstance();
                instanceContainer.put(className, instance);
                return instance;
            } else {
                return instanceContainer.get(className);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;

    }

    public static void main(String[] args) {
        final Object instance1 = Singleton9.getInstance(JavaCourse.class.getName());
        final Object instance2 = Singleton9.getInstance(JavaCourse.class.getName());
        System.out.println(instance1);
        System.out.println(instance2);
        System.out.println(instance1 == instance2);
    }
}
